<template>
  <div class="main">
    <div class="price">请支付：&yen;{{ $route.query.price }}</div>
    <div id="paypal-bottons"></div>

  </div>

</template>
<script>
import { capture_order, create_order } from "@/api/order_api";
import { loadScript } from "@paypal/paypal-js";

export default{
  methods:{
    
    async constructButton(){
      let paypal;
      try {
          paypal = await loadScript({ 
            clientId: "AcvFGUXzEpn4-d70fwpP71o3c12luHZ9ourO7vBRADe-6fAMkXyOy-X2rtchvXZChWUAyjVB8_Jmel0T" ,
            disableFunding:['credit','card'] // 禁止出现的按钮
          });
      } catch (error) {
          console.error("failed to load the PayPal JS SDK script", error);
      }
      if (paypal) {
          try {
              await paypal.Buttons(
                {
                  style:{
                  height:40,
                  label:'paypal'
                },
                // 创建订单
                createOrder:async (data,actions)=>{
                  try {
                    console.log("bbbbb");
                    
                    const {data:orderData} = await create_order(JSON.parse(this.$route.query.data))
                    if (orderData.id) {
                      return orderData.id;
                    }
                    const errorDetail = orderData?.details?.[0];
                    const errorMessage = errorDetail
                      ? `${errorDetail.issue} ${errorDetail.description} (${orderData.debug_id})`
                      : JSON.stringify(orderData);

                    throw new Error(errorMessage);
                  } catch (error) {
                    console.error(error);
                    resultMessage(`Could not initiate PayPal Checkout...<br><br>${error}`);
                  }
                },
                // 捕获订单
                onApprove:async (data,actions)=>{
                  try{
                    const {data:orderData} = await capture_order(data.orderID)
                    const errorDetail = orderData?.details?.[0];
                    if (errorDetail?.issue === "INSTRUMENT_DECLINED") {
                      return actions.restart();
                    } else if (errorDetail) {
                      throw new Error(`${errorDetail.description} (${orderData.debug_id})`);
                    } else if (!orderData.purchase_units) {
                      throw new Error(JSON.stringify(orderData));
                    } else {
                      const transaction =
                        orderData?.purchase_units?.[0]?.payments?.captures?.[0] ||
                        orderData?.purchase_units?.[0]?.payments?.authorizations?.[0];
                        console.log(transaction);
                        
                        if(transaction.status=='COMPLETED'){
                          this.$message({
                            type:'success',
                            message:'支付成功'
                          })
                          this.$router.push('/load')
                        }else{
                          this.$message({
                            type:'error',
                            message:'支付失败'
                          })
                        }
                    }
                  } catch (error) {
                    this.$message({
                      type:'error',
                      message:'Sorry, your transaction could not be processed'
                    })
                  }
                }
              },
              ).render("#paypal-bottons");
          } catch (error) {
                    this.$message({
                      type:'error',
                      message:'failed to render the PayPal Buttons'
                    })
          }
      }
      
      
    }
  
  },
}
</script>
<style lang="scss" scoped>
.main{
  display: flex;
  flex-direction: column;
  align-items: center;
  .price{
    font-size: 30px;
    margin-bottom: 100px;
    color:red;
  }
}

</style>